#include "MIKE_ZHOU_STM32_HAL.h"
#include <string.h>

#ifdef HAL_UART_MODULE_ENABLED
void MZ_STM32_HAL_UART_HalfDuplexTransmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
	HAL_UART_Abort(huart);
	HAL_HalfDuplex_EnableTransmitter(huart);
	HAL_UART_Transmit(huart,pData,Size,Timeout);
}

void MZ_STM32_HAL_UART_HalfDuplexTransmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
	HAL_UART_Abort(huart);
	HAL_HalfDuplex_EnableTransmitter(huart);
	HAL_UART_Transmit_IT(huart,pData,Size,Timeout);
}

void MZ_STM32_HAL_UART_HalfDuplexTransmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
	HAL_UART_Abort(huart);
	HAL_HalfDuplex_EnableTransmitter(huart);
	HAL_UART_Transmit_DMA(huart,pData,Size,Timeout);
}

void MZ_STM32_HAL_UART_HalfDuplexReceive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
	HAL_UART_Abort(huart);
	HAL_HalfDuplex_EnableReceiver(huart);
	HAL_UART_Receive(huart,pData,Size,Timeout);
}

void MZ_STM32_HAL_UART_HalfDuplexReceive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
	HAL_UART_Abort(huart);
	HAL_HalfDuplex_EnableReceiver(huart);
	HAL_UART_Receive_IT(huart,pData,Size);
}

void MZ_STM32_HAL_UART_HalfDuplexReceive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
	HAL_UART_Abort(huart);
	HAL_HalfDuplex_EnableReceiver(huart);
	HAL_UART_Receive_DMA(huart,pData,Size);
}


void MZ_STM32_HAL_UART_Reset(UART_HandleTypeDef *huart)
{
	__HAL_UART_FLUSH_DRREGISTER(huart); // 清空数据寄存器
	// 中止可能存在的传输
    HAL_UART_Abort(huart);  // 停止所有收发操作
    __HAL_UART_DISABLE(huart);          // 禁用UART
    __HAL_UART_ENABLE(huart);           // 重新使能UART    
	__HAL_UART_FLUSH_DRREGISTER(huart); // 清空数据寄存器    
}

bool MZ_STM32_HAL_UART_ConfigureBaud(UART_HandleTypeDef *huart,uint32_t baud)
{
    UART_HandleTypeDef uart;   
    huart->Init.BaudRate = baud;
    memcpy(&uart,huart,sizeof(UART_HandleTypeDef));
	HAL_UART_DeInit(huart);
    memcpy(huart,&uart,sizeof(UART_HandleTypeDef));
    if (HAL_UART_Init(huart) != HAL_OK)
    {
        return false;
    }
    
    MZ_STM32_HAL_UART_Reset(huart);
  
	return true;
}

#endif

